<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="权限名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click.native="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">新增权限</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row>
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="权限名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="权限路径">
        <template slot-scope="scope">
          {{ scope.row.path }}
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template slot-scope="scope">
          {{ scope.row.type | typeLableFilter }}
        </template>
      </el-table-column>
      <el-table-column label="模式">
        <template slot-scope="scope">
          {{ scope.row.mode | modeLableFilter }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusValueFilter">{{ scope.row.status | statusLableFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="scope.row.type === 1" type="primary" size="mini" @click="handleCreateChild(scope.row)">增加子集</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="privilege" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="privilege.name" placeholder="权限名称"/>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="privilege.path" placeholder="路径"/>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="privilege.type">
            <el-radio-button v-for="item in typeTypeOptions" :key="item.display_name" :label="item.key" >{{ item.display_name }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模式" prop="mode">
          <el-radio-group v-model="privilege.mode">
            <el-radio-button v-for="item in modeTypeOptions" :key="item.display_name" :label="item.key" >{{ item.display_name }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="privilege.status">
            <el-radio-button v-for="item in statusTypeOptions" :key="item.display_name" :label="item.key" >{{ item.display_name }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getPrivilegeList, createPrivilege, updatePrivilege, deletePrivilege } from '@/api/privilege'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const typeTypeOptions = [
  { key: 1, display_name: '菜单' },
  { key: 2, display_name: '元素' }
]
const typeTypeKeyValue = typeTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const modeTypeOptions = [
  { key: 1, display_name: '内链' },
  { key: 2, display_name: '外链' }
]
const modeTypeKeyValue = modeTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const statusTypeOptions = [
  { key: 1, display_name: '启用' },
  { key: 0, display_name: '停用' }
]
const statusTypeKeyValue = statusTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Role',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusValueFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    },
    typeLableFilter(type) {
      return typeTypeKeyValue[type]
    },
    modeLableFilter(mode) {
      return modeTypeKeyValue[mode]
    },
    statusLableFilter(status) {
      return statusTypeKeyValue[status]
    }
  },
  data() {
    return {
      radio3: 1,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: ''
      },
      privilege: {
        id: undefined,
        parentId: 0,
        name: '',
        path: '',
        level: 1,
        type: 1,
        mode: 1,
        status: 1
      },
      dialogFormVisible: false,
      typeTypeOptions,
      modeTypeOptions,
      statusTypeOptions,
      dialogStatus: '',
      textMap: {
        update: '修改权限',
        create: '新增权限'
      },
      rules: {
        name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
        path: [{ required: true, message: '请输入路径', trigger: 'blur' }] // ,
        // type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        // mode: [{ required: true, message: '请选择模式', trigger: 'change' }],
        // status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getPrivilegeList(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetPrivilege() {
      this.privilege = {
        id: undefined,
        parentId: 0,
        name: '',
        path: '',
        level: 1,
        type: 1,
        mode: 1,
        status: 1
      }
    },
    handleCreate() {
      this.resetPrivilege()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          createPrivilege(this.privilege).then(response => {
            this.privilege.id = response.data.data
            this.list.unshift(this.privilege)
            this.total = this.total + 1
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.privilege = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreateChild(row) {
      this.resetPrivilege()
      this.privilege.level = this.privilege.level + 1
      this.privilege.parentId = row.id
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.privilege)
          updatePrivilege(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.privilege.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.privilege)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.privilege = Object.assign({}, row) // copy obj
      const tempData = Object.assign({}, this.privilege)
      this.$confirm('您确定删除吗？').then(_ => {
        deletePrivilege(tempData).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.total = this.total - 1
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(_ => {

      })
    }
  }
}
</script>
